import { ref, reactive } from 'vue'

// 用户信息接口
export interface UserInfo {
  avatar: string
  nickname: string
  idNumber: string
  birthDate: string
  phone: string
  address: string
  email: string
  gender: string
  bloodType: string
}

// 默认用户信息
const defaultUserInfo: UserInfo = {
  avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
  nickname: '大毛蛋',
  idNumber: '100000000000000000',
  birthDate: '1995-09-21',
  phone: '15810000000',
  address: '北京市海淀区中关村详细信息',
  email: 'damaodan@modao.com',
  gender: '女士',
  bloodType: 'AB+'
}

// 从 localStorage 获取用户信息
const getUserInfoFromStorage = (): UserInfo => {
  try {
    const stored = localStorage.getItem('userInfo')
    return stored ? { ...defaultUserInfo, ...JSON.parse(stored) } : defaultUserInfo
  } catch {
    return defaultUserInfo
  }
}

// 保存用户信息到 localStorage
const saveUserInfoToStorage = (userInfo: UserInfo) => {
  try {
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  } catch (error) {
    console.error('保存用户信息失败:', error)
  }
}

// 用户信息状态
const userInfo = reactive<UserInfo>(getUserInfoFromStorage())

// 更新用户信息
const updateUserInfo = (newInfo: Partial<UserInfo>) => {
  Object.assign(userInfo, newInfo)
  saveUserInfoToStorage(userInfo)
}

// 更新头像
const updateAvatar = (avatarUrl: string) => {
  userInfo.avatar = avatarUrl
  saveUserInfoToStorage(userInfo)
}

// 重置用户信息
const resetUserInfo = () => {
  Object.assign(userInfo, defaultUserInfo)
  saveUserInfoToStorage(userInfo)
}

export function useUserData() {
  return {
    userInfo,
    updateUserInfo,
    updateAvatar,
    resetUserInfo
  }
} 